import json
import requests

cloudreve_url = "https://qitapan.cn"


def login(username, password):
    # 登录
    url = cloudreve_url + "/api/v3/user/session"
    data = json.dumps({
        "userName": username,
        "Password": password,
        "captchaCode": ""
    })
    data = json.dumps({
        "userName": "",
        "Password": "",
        "captchaCode": ""
    })
    response = requests.post(url, data)
    if response.json()['code'] != 40001:
        return response.cookies['cloudreve-session']
    else:
        print("用户名或密码错误")
        exit()


def get_user_files(dir_path, user_session, path):
    # 获取文件
    dir_path = dir_path + path
    headers = {
        'cookie': 'cloudreve-session=' + user_session
    }
    resource = requests.get(dir_path, headers=headers)
    print(dir_path)
    return resource.json()['data']['objects']


def get_download_file_url(file_id, user_session):
    # 获取下载链接
    url = cloudreve_url + "/api/v3/file/download/" + file_id
    headers = {
        'cookie': 'cloudreve-session=' + user_session
    }
    resource = requests.put(url, headers=headers)
    return resource.json()


def download_file(download_url, file_name):
    # 下载文件
    print(f"开始下载:{file_name}")
    f = open("log.txt", "a")
    f.write(f"开始下载:{file_name}")
    r = requests.get(download_url)
    if r.status_code != 404:
        with open(file_name, "wb") as code:
            code.write(r.content)
        f.write(f"{file_name}:下载完成\n\r")
        print(f"{file_name}:下载完成\n\r")
    else:
        f.write(f"{download_url}:文件不存在\n\r")
        print(f"{download_url}:文件不存在\n\r")


def aria2_dow_one_file(download_url, user_session, dst):
    # 离线下载
    url = cloudreve_url + "/api/v3/aria2/url"
    headers = {
        'cookie': 'cloudreve-session=' + user_session
    }
    data = json.dumps(
        {
            "url": download_url,
            "dst": dst
        }
    )
    resource = requests.post(url, headers=headers, data=data)
    r_json = resource.json()
    if r_json['code'] != 0:
        print("错误：" + r_json['msg'])
    else:
        print(download_url + "-成功添加至离线下载中")
    return resource.json()


def aria2_dow_many_file(dow_files_name, user_session, dst):
    # 离线下载多文件
    url = cloudreve_url + "/api/v3/aria2/url"
    headers = {
        'cookie': 'cloudreve-session=' + user_session
    }
    f = open(dow_files_name, 'r', encoding='utf-8')
    for one_line in f:
        data = json.dumps(
            {
                "url": one_line.splitlines()[0],
                "dst": dst
            }
        )
        resource = requests.post(url, headers=headers, data=data)
        r_json = resource.json()
        if r_json['code'] != 0:
            print("错误：" + r_json['msg'])
        else:
            print(one_line + "-成功添加至离线下载中")
    return "OK"


user_dir_path = [cloudreve_url + "/api/v3/directory"]  # 用户历史目录
user_now_dir_path = cloudreve_url + "/api/v3/directory"  # 用户当前目录


def user_cd(path):
    # cd 命令
    user_dir_path.append(user_now_dir_path + path)
    return user_now_dir_path + path


def help_me():
    # 帮助
    print("V0.0.2 测试版")
    print("help 帮助")
    print("ls 列出文件目录 ls [/目录名]")
    print("cd 定位到文件夹 cd <目录名>")
    print("dow 下载文件 dow <文件名>")
    print("mkdir 创建目录 mkdir <目录名>")
    print("lx 添加离线下载 lx [-o][-m] <URL/FTP/磁力/文件地址>， 详情请输入 lx help")


def lx_help():
    # 离线下载帮助
    print("离线下载命令帮助")
    print("该命令用于添加离线下载功能，登录用户所在的用户组开放离线下载功能")
    print("命令如下:")
    print("lx -o URL \t 该命令用于添加单文件到离线下载组中 例：lx -o https://a.com/1.zip")
    print("lx -m file \t 该命令用于添加文件列表中的所有文件到离线下载组中 例：lx -m 离线下载列表.txt 注意! 列表必须是一行一个文件")


def user_mkdir(url, user_session, folders_name):
    headers = {
        'cookie': 'cloudreve-session=' + user_session
    }
    data = json.dumps({"path": "/" + folders_name})
    r = requests.put(url, data=data, headers=headers)
    return r.json()


username = str(input("请输入用户名:\n"))
password = str(input("请输入密码:\n"))
session = login(username, password)
if session != "":
    print("登录成功")

files_all_json = []
help_me()
while True:
    control_code = input("请输入操作码:\n")
    control_code = control_code.split(" ")
    c_code = control_code[0].upper()
    if c_code == "LS":
        if len(control_code) == 2:
            control_code_1 = control_code[1]
        else:
            control_code_1 = ""
        get_user_files_json = get_user_files(user_now_dir_path, session, control_code_1)
        for item in get_user_files_json:
            files_all_json.append(item)
            print("文件名：" + item['name'] + "\t" + "文件类型：" + item['type'] + "\t" + "文件大小：" + str(item['size']))
    elif c_code == "DOW":
        for item in files_all_json:
            if item['name'] == control_code[1]:
                download_url_json = get_download_file_url(item['id'], session)
                if download_url_json['code'] != 40001:
                    download_file(download_url_json['data'], item['name'])
                else:
                    print("文件不存在")

    elif c_code == "CD":
        if control_code[1] == "../":
            # 上级目录
            print(user_dir_path)
            user_now_dir_path = user_dir_path[len(user_dir_path) - 2]
            user_dir_path.pop()
        elif control_code[1] == "":
            user_now_dir_path = user_cd(control_code[1])
    elif c_code == "HELP":
        help_me()
    elif c_code == "EXIT":
        exit()
    elif c_code == "MKDIR":
        # 创建目录要求最后路径不带/
        a = user_mkdir(user_now_dir_path[0:len(user_now_dir_path) - 1], session, control_code[1])
    elif c_code == "LX":
        if control_code[1] == "help":
            lx_help()
        elif control_code[1] == "-o":
            aria2_dow_one_file(control_code[2], session, input("请输入文件存储路径，\"/\"代表根目录:\n"))
        elif control_code[1] == "-m":
            aria2_dow_many_file(control_code[2], session, input("请输入文件存储路径，\"/\"代表根目录:\n"))
